package com.sltx.controller;

import com.sltx.controller.base.BaseController;
import com.sltx.service.ZsglService;
import com.sltx.util.ExcelUtil;
import com.sltx.util.PageData;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;


/**
 * 上传模板，下载数据
 */

@Controller
@Component
public class DownloadController extends BaseController {


    /****
     * 模板文件存放的目录
     */
    @Value("${baseDir}")
    private  String  baseDir ;

    @Resource
    private ZsglService zsglService;


    /**
     *
     *
     * @param fileUrl 图片的url路径
     * @param response
     * @return
     */
    @RequestMapping(value = "/download")
    public void downloadMedia(HttpServletResponse response, HttpServletRequest request,String fileUrl,String name) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //处理中文乱码
            request.setCharacterEncoding("UTF-8");
            String fileName = new String(fileUrl.getBytes("iso8859-1"),"UTF-8");
            //处理浏览器兼容
            response.setContentType("application/msexcel;charset=utf-8");//定义输出类型
            Enumeration enumeration = request.getHeaders("User-Agent");
            String browserName = (String) enumeration.nextElement();
            boolean isMSIE = browserName.contains("MSIE");

            if (isMSIE) {
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF8"));
            } else {
                response.addHeader("Content-Disposition", "attachment;fileName=" + new String(name.getBytes("gb2312"), "ISO8859-1"));
            }
            //url地址如果存在空格，会导致报错！  解决方法为：用+或者%20代替url参数中的空格。
            fileName = fileName.replace(" ", "%20");

            //图片下载
            URL url = new URL(fileName);
            URLConnection conn = url.openConnection();
            outputStream = response.getOutputStream();
            inputStream = conn.getInputStream();

            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            System.err.println(e);
        }finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }

    /**
     * 下载word文档
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/downLoadWord")
    @ResponseBody
    public void downLoadWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            String path = baseDir + "/shuishou .xlsx";
            System.out.println(" filepath==" + path);
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }


    /**
     * 下载指标考核部门表格
     * @param response
     * @return
     */
    @RequestMapping("/DownloadDept")
    @ResponseBody
    public Object DownloadDept(HttpServletResponse response){
        PageData pd = this.getPageData();

        String dept = pd.get("dept").toString();
        // 获取列名
        List<String> rowNameList = Arrays.asList("部门名称",
                "高精尖目标值",
                "新增高精尖企业数量",
                "重点目标值",
                "新增重点企业数量",
                "外资目标值",
                "新增外资企业数量",
                "贡献度目标值",
                "引进企业累计区级综合经济贡献",
                "加分",
                "得分",
                "已完成全年目标");

        // 需要写入的数据
        List<Map<String, String>> list = new ArrayList<>();

        if (dept.equals("产业主管部门")) {
            List<Map<String, Object>> cyzgList = zsglService.getCyzgList(pd);
            for (Map m:cyzgList){
                Map<String, String> map = new HashMap<>();
                String ent_yjqydw = m.get("ent_yjqydw").toString();
                String gjj_target = m.get("gjj_target").toString();
                String gjjNum = m.get("gjjNum").toString();
                String zd_target = m.get("zd_target").toString();
                String zdqyNum = m.get("zdqyNum").toString();
                String wz_target = m.get("wz_target").toString();
                String wzqyNum = m.get("wzqyNum").toString();
                String gxd_target = m.get("gxd_target").toString();
                String gxd_yjqy = m.get("gxd_yjqy").toString();
                String jf = m.get("jf").toString();
                String jxdf = m.get("jxdf").toString();
                String wcmb2021 = m.get("wcmb2021").toString();
                map.put("部门名称", ent_yjqydw);
                map.put("高精尖目标值", gjj_target);
                map.put("新增高精尖企业数量", gjjNum);
                map.put("重点目标值", zd_target);
                map.put("新增重点企业数量", zdqyNum);
                map.put("外资目标值", wz_target);
                map.put("新增外资企业数量", wzqyNum);
                map.put("贡献度目标值", gxd_target);
                map.put("引进企业累计区级综合经济贡献", gxd_yjqy);
                map.put("加分", jf);
                map.put("得分", jxdf);
                map.put("已完成全年目标", wcmb2021);
                list.add(map);
            }

        }
        if (dept.equals("联合招商部门")){
            List<Map<String, Object>> lhzsList = zsglService.getLhzsList(pd);
            for (Map m:lhzsList){
                Map<String, String> map = new HashMap<>();
                String ent_yjqydw = m.get("ent_yjqydw").toString();
                String gjj_target = m.get("gjj_target").toString();
                String gjjNum = m.get("gjjNum").toString();
                String zd_target = m.get("zd_target").toString();
                String zdqyNum = m.get("zdqyNum").toString();
                String wz_target = m.get("wz_target").toString();
                String wzqyNum = m.get("wzqyNum").toString();
                String gxd_target = m.get("gxd_target").toString();
                String gxd_yjqy = m.get("gxd_yjqy").toString();
                String jf = m.get("jf").toString();
                String jxdf = m.get("jxdf").toString();
                String wcmb2021 = m.get("wcmb2021").toString();
                map.put("部门名称", ent_yjqydw);
                map.put("高精尖目标值", gjj_target);
                map.put("新增高精尖企业数量", gjjNum);
                map.put("重点目标值", zd_target);
                map.put("新增重点企业数量", zdqyNum);
                map.put("外资目标值", wz_target);
                map.put("新增外资企业数量", wzqyNum);
                map.put("贡献度目标值", gxd_target);
                map.put("引进企业累计区级综合经济贡献", gxd_yjqy);
                map.put("加分", jf);
                map.put("得分", jxdf);
                map.put("已完成全年目标", wcmb2021);
                list.add(map);
            }
        }

        try {
            ExcelUtil.excelPort(dept,rowNameList, list, response);
            return "下载成功";
        }catch (Exception e){
            return "下载失败";
        }

    }


    /**
     * 下载指标考核对应部门引进企业表格
     * @param response
     * @return
     */
    @RequestMapping("/DownloadEnt")
    @ResponseBody
    public Object DownloadEnt(HttpServletResponse response){
        PageData pd = this.getPageData();

        String dept = pd.get("ent_yjqydw").toString() + "引入企业列表";
        // 获取列名
        List<String> rowNameList = Arrays.asList("企业名称",
                "企业法人",
                "注册资本",
                "统一社会信用代码",
                "成立时间",
                "注册地址",
                "实际经营地址",
                "经营范围",
                "高精尖产业类别",
                "重点企业类别",
                "外资企业",
                "引进形式",
                "提供企业单位",
                "引进企业单位",
                "企业联系人",
                "企业联系电话",
                "区级综合经济贡献",
                "企业简介",
                "提交时间",
                "税款金额",
                "增减额",
                "增幅",
                "区级",
                "行业",
                "行业大类",
                "年份",
                "月份"
                );

        // 需要写入的数据
        List<Map<String, String>> list = new ArrayList<>();

        List<Map<String, Object>> deptQyList = zsglService.getDeptQyList(pd);
        if(deptQyList.size() >0) {
            for (Map<String, Object> m : deptQyList) {
                Map<String, String> map = new HashMap<>();
                if (m.get("entname") != null) {
                    map.put("企业名称", m.get("entname").toString());
                }
                if (m.get("ent_fr") != null) {
                    map.put("企业法人", m.get("ent_fr").toString());
                }
                if (m.get("ent_zczb") != null) {
                    map.put("注册资本", m.get("ent_zczb").toString());
                }
                if (m.get("uniscid") != null) {
                    map.put("统一社会信用代码", m.get("uniscid").toString());
                }
                if (m.get("ent_date") != null) {
                    map.put("成立时间", m.get("ent_date").toString());
                }
                if (m.get("ent_dz") != null) {
                    map.put("注册地址", m.get("ent_dz").toString());
                }
                if (m.get("ent_retitle") != null) {
                    map.put("实际经营地址", m.get("ent_retitle").toString());
                }
                if (m.get("ent_title") != null) {
                    map.put("经营范围", m.get("ent_title").toString());
                }
                if (m.get("ent_gjj_xl") != null) {
                    map.put("高精尖产业类别", m.get("ent_gjj_xl").toString());
                }
                if (m.get("ent_zdqy_xl") != null) {
                    map.put("重点企业类别", m.get("ent_zdqy_xl").toString());
                }
                if (m.get("ent_sfwz") != null) {
                    map.put("外资企业", m.get("ent_sfwz").toString());
                }
                if (m.get("ent_yjfs") != null) {
                    map.put("引进形式", m.get("ent_yjfs").toString());
                }
                if (m.get("ent_xxtgdw") != null) {
                    map.put("提供企业单位", m.get("ent_xxtgdw").toString());
                }
                if (m.get("ent_yjqydw") != null) {
                    map.put("引进企业单位", m.get("ent_yjqydw").toString());
                }
                if (m.get("ent_person") != null) {
                    map.put("企业联系人", m.get("ent_person").toString());
                }
                if (m.get("ent_tel") != null) {
                    map.put("企业联系电话", m.get("ent_tel").toString());
                }
                if (m.get("gxd") != null) {
                    map.put("区级综合经济贡献", m.get("gxd").toString());
                }
                if (m.get("ent_jj") != null) {
                    map.put("企业简介", m.get("ent_jj").toString());
                }
                if (m.get("submit_date") != null) {
                    map.put("提交时间", m.get("submit_date").toString());
                }
                if (m.get("skje") != null) {
                    map.put("税款金额", m.get("skje").toString());
                }
                if (m.get("zje") != null) {
                    map.put("增减额", m.get("zje").toString());
                }
                if (m.get("zf") != null) {
                    map.put("增幅", m.get("zf").toString());
                }
                if (m.get("qj") != null) {
                    map.put("区级", m.get("qj").toString());
                }
                if (m.get("industry") != null) {
                    map.put("行业", m.get("industry").toString());
                }
                if (m.get("industry_dl") != null) {
                    map.put("行业大类", m.get("industry_dl").toString());
                }
                if (m.get("year") != null) {
                    map.put("年份", m.get("year").toString());
                }
                if (m.get("month") != null) {
                    map.put("月份", m.get("month").toString());
                }
                list.add(map);
            }
        }else{
            Map<String, String> map = new HashMap<>();
            list.add(map);
        }
        try {
            ExcelUtil.excelPort(dept,rowNameList, list, response);
            return "下载成功";
        }catch (Exception e){
            return "下载失败";
        }
    }
}

